package application

import (
	"errors"
	"sync"
)

type Point struct {
	index    uint8
	mux      *sync.RWMutex
	children map[string]string
	total    uint8
	names    []string
}

func NewPoint() *Point {
	return &Point{
		index:    1,
		children: make(map[string]string),
		total:    0,
		mux:      new(sync.RWMutex),
	}
}

func (p *Point) Append(key, val string) {
	p.mux.Lock()
	defer p.mux.Unlock()
	p.total += 1
	p.names = append(p.names, key)
	p.children[key] = val
}

func (p *Point) Get() (string, string, error) {
	p.mux.RLock()
	defer p.mux.RUnlock()
	if p.total == 0 {
		return "", "", errors.New("not avaiable service point")
	}
	p.index %= p.total
	name := p.names[p.index]
	p.index += 1
	if _, ok := p.children[name]; !ok {
		return "", "", errors.New("not avaiable service point in child")
	}
	return name, p.children[name], nil
}

func (p *Point) Delete(key string) error {
	p.mux.Lock()
	defer p.mux.Unlock()
	for i, v := range p.names {
		if v == key {
			p.total -= 1
			p.names = append(p.names[:i], p.names[i+1:]...)
			if _, ok := p.children[key]; ok {
				return errors.New("not avaiable service point in child")
			}
			return nil
		}
	}
	return nil
}
